package forms

import (
	"errors"
	valid "github.com/go-ozzo/ozzo-validation"
	"github.com/mojocn/base64Captcha"
	"titargo/models"
)

type LoginForm struct {
	Username   string `form:"username",json:"user"`
	Password   string `form:"password",json:"password"`
	VerifyCode string `form:"verifyCode",json:"password"`
	user       *models.User
}

func (l *LoginForm) Validate() error {
	err := valid.ValidateStruct(l,
		valid.Field(&l.Username, valid.Required.Error("用户名不能为空")),
		valid.Field(&l.Password, valid.Required.Error("密码不能为空")),
		valid.Field(&l.VerifyCode, valid.Required.Error("验证码不能为空")),
	)
	if err != nil {
		return err
	}

	if !base64Captcha.VerifyCaptcha("verifyKey", l.VerifyCode) {
		return errors.New("验证码错误")
	}

	db := models.GetEngine()
	var user models.User
	has,err := db.Where("username=? and password=?",l.Username,l.Password).Get(&user)
	if err != nil{
		return err
	}

	if has==false {
		return errors.New("用户名或密码错误")
	}
	l.user = &user
	return nil
}

func (l LoginForm) GetUser() *models.User {
	return l.user
}
